package com.hackerchat.server;

import java.io.*;
import java.net.*;
import java.util.*;

import com.hackerchat.utils.SCConstants;
import com.hackerchat.utils.SCLog;


public class SCServer {

	private ServerSocket ss;
	private Hashtable<Socket,DataOutputStream> outputStreams = new Hashtable<Socket,DataOutputStream>();

	public SCServer() {

	}

	public void listen() throws IOException {
		this.ss = new ServerSocket( SCConstants.PORT );

		while( true ) {

			try {
				SCLog.writeMessage( "Server ready for connection at " + this.ss );
				
				Socket s = ss.accept();
	
				SCLog.writeMessage( "Connection from " + s + " accepted" );
	
				DataOutputStream dos = new DataOutputStream( s.getOutputStream() );
				this.outputStreams.put( s, dos );
	
				new SCClientHandler( this, s );
				
			} catch( IOException e ) {
				SCLog.writeErrorMessage( "Conection lost" );
			}
		}
	}

	public Enumeration<DataOutputStream> getOutputStreams() {
		return this.outputStreams.elements();
	}

	public void sendToAll( String message ) {
		synchronized( this.outputStreams ) {
			for( Enumeration<DataOutputStream> e = this.getOutputStreams(); e.hasMoreElements();) {
				DataOutputStream dos = (DataOutputStream) e.nextElement();
				try {
					dos.writeUTF( message );
				} catch (IOException ie) {
					System.out.println( ie );
				}
			}
		}
	}

	public void removeConnection( Socket s ) {
		synchronized( this.outputStreams ) {
			System.out.println( "Removing connection to " + s );
			this.outputStreams.remove( s );
			try {
				s.close();
			} catch (IOException ie) {
				System.out.println("Error closing " + s);
				ie.printStackTrace();
			}
		}
	}
}
